﻿using System;
using System.Windows.Automation;
using System.Reflection;
using System.Diagnostics;

namespace RobotUI.Win32Layer
{
	/// <summary>
	/// Win32 window
	/// </summary>
	public class Window
	{
		
		private AutomationElement _elm;
		private IntPtr _handle;
		
		
		public Window(AutomationElement elm)
		{
			if (elm==null) throw new ArgumentNullException("Unable to create Win32 Window, not Element specified");
			_elm = elm;
			_handle = (IntPtr)elm.Current.NativeWindowHandle;
		}
		
		
		public void SetForegroundWindow(int retries)
		{
			bool success = false;
			while (retries>=0)
			{
				try
    			{

	            	// Get the Process ID for the element we are trying to
	            	// set as the foreground element
	            	int other_id = Win32.GetWindowThreadProcessId (_handle, IntPtr.Zero);
	
	            	// Get the Process ID for the current process
	            	int this_id = Win32.GetWindowThreadProcessId (Process.GetCurrentProcess ().Handle, IntPtr.Zero);
	
	            	// Attach the current process's input to that of the 
	            	// given element. We have to do this otherwise the
	            	// WM_SETFOCUS message will be ignored by the element.
	            	Win32.AttachThreadInput (this_id, other_id, true);
	
	            	// Make the Win32 call
	            	IntPtr previous = Win32.SetForegroundWindow(_handle);
					//check result
	            	success = !(IntPtr.Zero.Equals(previous));
	            	if (success) break;
        		}
				catch { }
				System.Threading.Thread.Sleep(500);
				retries--;
			}
			if (!success) throw new Exception("Unable to set foreground window");
		}
		
		
	}
}
